//Copyright 2012 Trevin Liberty
//GNU GPL v3
//Author: Trevin Liberty

#include "Pathing Thread.h"

//Function for pathing thread. Checks queueIn for and entries. 
//Creates paths for said entries and pushs the completed paths into queueOut.
static void *Pathing_Thread(ALLEGRO_THREAD *thr, void *arg) {
	AStar* astar = (AStar*) arg;

	CompletedPath *path = NULL;
	PathingQueueEntry *entry = NULL;

	while(!al_get_thread_should_stop(thr)) {
		//So the thread doesn't spam queueIN and make it more of
		//	a bottleneck than it already is.
		al_rest(0.05);

		if(al_get_thread_should_stop(thr)) {
			return 0;
		}

		entry = astar->queueInGet();
		if(entry == NULL)
			continue;

		//Create Path
		path = new CompletedPath();
		path->path = astar->getPath(entry->start, entry->dest, thr);
		path->e = entry->e;

		//Put completed path in queueOut
		astar->addCompletedPath(path);

		delete entry;
	}
	return 0;
 }

PathingThread::PathingThread(AStar* astar) {
	this->astar = astar;

	for(int i = 0; i < NUM_THREADS; i++) {
		thread[i] = al_create_thread(Pathing_Thread, astar);
		al_start_thread(thread[i]);
	}
}

PathingThread::~PathingThread() {
	for(int i = 0; i < NUM_THREADS; i++) {
		al_set_thread_should_stop(thread[i]);
	}
	for(int i = 0; i < NUM_THREADS; i++) {
		al_destroy_thread(thread[i]);
	}
}